/*
 * @Author: vinny
 * @Date: 2024-09-01 17:34:23
 * @Desc: localStorage
 */

class Storage {
  constructor(name = import.meta.env.VITE_LOCAL_STORAGE_KEY_PREFIX) {
    this.name = name
    this.init()
  }

  private name: string
  private init() {
    Object.keys(localStorage).forEach((item) => {
      if (item.startsWith(this.name)) {
        this.hasItem(item.replace(this.name, ''))
      }
    })
  }
  /**
   * localStorage存储
   * @param key 存储名称
   * @param value 存储值
   * @param time 存储时间
   */
  public setItem(key: string, value?: any, time?: number) {
    if (value === undefined) value = null
    const _key: any = this.name + key
    const _value: any = { value }
    time && (_value.time = time * 1000 + new Date().getTime())
    localStorage.setItem(_key, JSON.stringify(_value))
  }
  /**
   *  获取会话
   * @param key 存储名称
   * @returns
   */
  public getItem(key: string) {
    if (this.hasItem(key)) {
      const item = localStorage.getItem(this.name + key);
      if (item !== null) {
        return JSON.parse(item).value;
      }
    }
    return null
  }
  /**
   * 删除会话
   * @param key 存储名称
   */
  public removeItem(key: string) {
    localStorage.removeItem(this.name + key)
  }
  /**
   * 清空所有会话
   */
  public clear() {
    Object.keys(localStorage).forEach((item) => {
      if (item.startsWith(this.name)) {
        localStorage.removeItem(item)
      }
    })
  }
  /**
   * 所有会话长度
   */
  public getLength() {
    return Object.keys(localStorage).length
  }
  /**
   * 判断是否存在某个会话，当前时间>存储时间删除会话
   */
  public hasItem(key: string) {
    const _key = this.name + key
    if (localStorage.getItem(_key)) {
      const item = localStorage.getItem(_key);
      if (item !== null) {
        const _time = JSON.parse(item).time
        if (new Date().getTime() > _time) {
          localStorage.removeItem(_key)
          return false
        }
        return true
      } else {
        return false
      }
    }
  }
}
export default Storage
